package com.study.base.io.nio.multiselector;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * 一个serverchannel 注册到多个selector中
 * Created by tan on 2017/7/19.
 */
//如果一个连接 连接serverchannel .多个selector的select都会选到吗?
//selector是不是线程安全的?   [NIO中SELECTOR的工作原理](http://www.cnblogs.com/huaf/archive/2011/02/12/2373002.html)
//阻塞了的select可以通过调用selector的wakeup方法来唤醒。
//[nio框架中的多个Selector结构](http://www.iteye.com/topic/482269)
//	[mina架构分析 (NIO 网络接口)](http://www.iteye.com/topic/1129974)
public class MultiSelectorServer {
	private ServerSocketChannel serverSocket;
	private List<Selector> selectors;

	private List<Thread> threads;

	public MultiSelectorServer(int port, int selectorNum) throws IOException {
		serverSocket = ServerSocketChannel.open();
		serverSocket.bind(new InetSocketAddress("127.0.0.1", port));
		serverSocket.configureBlocking(false);

		selectors = new ArrayList<>();
		threads = new ArrayList<>();
		for (int i = 0; i < selectorNum; i++) {
			Selector selector = Selector.open();

			serverSocket.register(selector, SelectionKey.OP_ACCEPT);
			selectors.add(selector);


			Thread thread = new Thread(new Reactor(selector, serverSocket));
			threads.add(thread);
			thread.start();
		}
	}

	public static void main(String[] args) throws IOException {
		MultiSelectorServer server = new MultiSelectorServer(82, 4);
	}
}
